package com.moogene.android.engine.animlite;

import android.util.Log;

public class AlphaAnim extends Anime {
	private String TAG = "AlphaAnim";

	private int[] mToAlpha;
	private int mToAlphaIndex;
	private int[] mStepAlpha;

	AlphaAnim(DrawableWrapper drawableWrapper) {
        super(drawableWrapper);
    }

	public void start(int toAlpha, int stepAlpha) {
		start(drawableWrapper.getAlpha(), toAlpha, stepAlpha);
	}

	public void start(int fromAlpha, int toAlpha, int stepAlpha) {
		int[] tmpTo = new int[1];
		tmpTo[0] = toAlpha;
		int[] tmpStep = new int[1];
		tmpStep[0] = stepAlpha;
		start(fromAlpha, tmpTo, tmpStep);
	}

	public void start(int[] toAlpha, int stepAlpha[]) {
		start(drawableWrapper.getAlpha(), toAlpha, stepAlpha);
	}

	public void start(int fromAlpha, int[] toAlpha, int stepAlpha[]) {
		int i;
		int num = toAlpha.length;
		if (num != stepAlpha.length) {
			Log.d(TAG, "start(); length of the two param is illegal");
			throw new IllegalArgumentException("startAlpha(); length of the two param is illegal");
		}
		int tmpFrom;
		for (i = 0; i < num; i++) {
			if (i == 0) {
				tmpFrom = fromAlpha;
			} else {
				tmpFrom = toAlpha[i - 1];
			}
			if (toAlpha[i] > 0xFF || toAlpha[i] < 0) {
				Log.d(TAG, "startAlpha(); toAlpha[" + i + "]: " + toAlpha[i]);
				throw new IllegalArgumentException("startAlpha(); toAlpha is exceed the limit");
			}
			if (stepAlpha[i] > 0 && toAlpha[i] - tmpFrom <= 0
					|| stepAlpha[i] < 0 && toAlpha[i] - tmpFrom >= 0) {
				stepAlpha[i] = -stepAlpha[i];
			}
		}
		start();
		mToAlpha = toAlpha;
		mToAlphaIndex = 0;
		mStepAlpha = stepAlpha;
		drawableWrapper.setAlpha(fromAlpha);
	}

	@Override
	public void stop(){
		super.stop();
		drawableWrapper.setAlpha(0xFF);
	}

	public void setAlpha(int alpha) {
		drawableWrapper.setAlpha(alpha);
	}

	public int getAlpha() {
		return drawableWrapper.getAlpha();
	}

	@Override
	boolean nextFrame() {
		if(!super.nextFrame()){
			return false;
		}
		int curAlpha = drawableWrapper.getAlpha();
		curAlpha += mStepAlpha[mToAlphaIndex];
		if (curAlpha > 0xFF) {
			curAlpha = 0xFF;
		} else if (curAlpha < 0x0) {
			curAlpha = 0x0;
		}
		drawableWrapper.setAlpha(curAlpha);
		if (mStepAlpha[mToAlphaIndex] > 0
				&& mToAlpha[mToAlphaIndex] - curAlpha <= 0
				|| mStepAlpha[mToAlphaIndex] < 0
				&& mToAlpha[mToAlphaIndex] - curAlpha >= 0) {
			mToAlphaIndex++;
			if (mToAlphaIndex == mToAlpha.length) {
				pause();
			}
		}
		return true;
	}

}
